import 'dart:async';
import 'dart:convert';
import 'package:daily_score_mobile/model/student_info_model.dart';
import 'package:daily_score_mobile/model/student_model.dart';
import 'package:daily_score_mobile/util/params_util.dart';
import 'package:http/http.dart' as http;
import 'package:daily_score_mobile/constant/api_constant.dart';
import 'package:fluttertoast/fluttertoast.dart';

/// student 数据访问接口
/// @author: dingwen
/// @date: 2021/5/1
class StudentDao {
  /// 登录
  static Future<StudentModel> login({Map data}) async {
    final response = await http.post(Uri.parse(login_uri),
        headers: {"content-type": "application/json"}, body: jsonEncode(data)).catchError((onError){
      Fluttertoast.showToast(
        msg: "服务器异常，请联系管理员",
      );
    });
    Utf8Decoder utf8decoder = Utf8Decoder(); // fix 中文乱码
    var result = json.decode(utf8decoder.convert(response.bodyBytes));
    if (result['code'] == 200) {
      return StudentModel.fromJson(result['data']);
    } else if (result['code'] == 400 || result['code'] == 600) {
      Fluttertoast.showToast(
        msg: "登录失败，用户名或密码错误！",
      );
      return null;
    }else {
      Fluttertoast.showToast(
        msg: "服务器异常，请联系管理员",
      );
      return null;
    }
  }

  /// 个人信息
  static Future<StudentInfoModel> getStudentInfo({Map data}) async {
    String url = student_info_uri + ParamsUtil.mapToUri(data);
    final response = await http.get(
      Uri.parse(url),
    );
    Utf8Decoder utf8decoder = Utf8Decoder(); // fix 中文乱码
    var result = json.decode(utf8decoder.convert(response.bodyBytes));
    if (result['code'] == 200) {
      return StudentInfoModel.fromJson(result['data'][0]);
    } else {
      Fluttertoast.showToast(
        msg: "获取个人信息失败！",
      );
      return null;
    }
  }
}
